package com.sikadwafastdaisfondturbo.pretloan.adapter

import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaRecyclerViewAdapter
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaViewHolderHelper
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.HttpHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 10:43
 * @Annotation：流程常规通用适配器
 */
class ProcessCommonAdapter(recyclerView: RecyclerView?) : SikadwaRecyclerViewAdapter<JSONObject>(recyclerView) {

    //是否是通用样式，通用样式 tvTitle为加粗字体，非通用样式为默认字体
    var typeFaceStyle = Typeface.BOLD

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//时间选择
                return R.layout.item_process_common_select
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.item_process_common_mobile
            }
            "SELECT" -> {//选择
                return R.layout.item_process_common_select
            }
            else -> {//输入框
                return R.layout.item_process_common_input
            }
        }
    }

    override fun setItemChildListener(helper: SikadwaViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
        helper.setItemChildClickListener(R.id.imgMobileBook)//选择联系人
        helper.setItemChildClickListener(R.id.tvMobile)
    }

    override fun fillData(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val tvTitle = helper.getTextView(R.id.tvTitle)
        tvTitle.text = findKeywordColor(ContextCompat.getColor(mContext,R.color.FFFF4D3E),model.optString("title"),"*")
        tvTitle.setTypeface(Typeface.DEFAULT,typeFaceStyle)

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showSelectView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showContactMobileView(helper,position,model)
            }
            else -> {//输入框
                showInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showInputView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val editText = helper.getView<EditText>(R.id.editText)
        editText.setHint(hint)
        var showText = ""
        if (model.has("selectItem")){
            showText = model.optJSONObject("selectItem").optString("title")
        }
        editText.setText(showText)
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.setOnFocusChangeListener { v, hasFocus ->
            HHLog.e(">>>>>>是否失去焦点>>>>>>$hasFocus>>>>>>>${editText.text}")
            if (!hasFocus){
                HttpHelper.addEvent(String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName")),editText.text.toString())
            }
        }

        editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择类型
     */
    private fun showSelectView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.setHint(hint)
        if (model.has("selectItem")){
            tvValue.text = model.getJSONObject("selectItem").optString("title")
        }
    }

    /**
     * 联系电话
     */
    private fun showContactMobileView(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val textMobile = helper.getTextView(R.id.tvMobile)
        textMobile.setHint(hint)
        val editMobile = helper.getView<EditText>(R.id.editMobile)
        editMobile.setHint(hint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            textMobile.text = showValue
            editMobile.setText(showValue)
        }
        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                HttpHelper.addEvent(String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName")),editMobile.text.toString())
            }
        }
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isConfigAccount = Configs.getSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT)
        if(isConfigAccount){//审核账号 - 允许输入或选择
            textMobile.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            textMobile.visibility = View.VISIBLE
            editMobile.visibility = View.GONE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}